package com.xtwy.qrcodescan.zxing.camera.open;

import android.hardware.Camera;
import android.util.Log;

/*
 * -----------------------------------------------------------------
 * Copyright (C) 2014-2016, by your company, All rights reserved.
 * -----------------------------------------------------------------
 * 文    件: OpenCameraInterface.java
 * 作    者: 侯建军
 * 版    权: 1.0.0
 * 描    述: 打开相机接口
 * 创建时间: 2018/9/14 10:14
 * 更新时间：2018/9/14 10:14
 * -----------------------------------------------------------------
 * 2018/9/14 10:14 : 创建 OpenCameraInterface.java (侯建军);
 * -----------------------------------------------------------------
 */
public class OpenCameraInterface {

	static final String TAG = OpenCameraInterface.class.getName();

    /**
     * 打开摄相头
     * @param cameraId
     * @return
     */
	public static Camera open(int cameraId) {

		int numCameras = Camera.getNumberOfCameras();
		if (numCameras == 0) {
			Log.w(TAG, "No cameras!");
			return null;
		}

		boolean explicitRequest = cameraId >= 0;

		if (!explicitRequest) {
			// Select a camera if no explicit camera requested
			int index = 0;
			while (index < numCameras) {
				Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
				Camera.getCameraInfo(index, cameraInfo);
				if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
					break;
				}
				index++;
			}

			cameraId = index;
		}

		Camera camera;
		if (cameraId < numCameras) {
			Log.i(TAG, "Opening camera #" + cameraId);
			camera = Camera.open(cameraId);
		} else {
			if (explicitRequest) {
				Log.w(TAG, "Requested camera does not exist: " + cameraId);
				camera = null;
			} else {
				Log.i(TAG, "No camera facing back; returning camera #0");
				camera = Camera.open(0);
			}
		}

		return camera;
	}

    /**
     *
     * @return
     */
	public static Camera open() {
		return open(-1);
	}
}
